import wepy from 'wepy'

const wxRequest = async(params = {}, url, header) => {
  return new Promise(async (resolve, reject) => {
    const token = wepy.$instance.globalData.token
    const _header = { 'Authorization': token || '', 'ver': '1.0.0', 'Content-Type': 'application/json' }

    let data = params.query || {}

    try {
      let res = await wepy.request({
        url: url,
        method: params.method || 'POST',
        data: data,
        header: { ..._header, ...header },
        dataType: 'json'
      })

      // resolve(res.data)
      if (res) {
        const { data, statusCode } = res
        if (statusCode === 200 && data.code === 0) {
          resolve(res.data)
          console.log(res.data)
        } else if (statusCode === 401) {
          reject()
          wx.hideLoading()
          wx.removeStorageSync('TOKEN')
        } else {
          reject()
        }
      }
    } catch (error) {
      reject(error)
      console.log(error)
    } finally {
      // tip.loaded()
    }
  })
}

module.exports = {
  wxRequest
}
